<?php

namespace common\model;

use think\model\RelationModel;
use think\module\Module;

class TaskRepairOrderModel extends RelationModel
{
    //自动验证
    protected $_validate = [
        ['status', ['default', 'active', 'deny', 'done', 'closed'], '', self::EXISTS_VALIDATE, 'in'], // 任务类型
        ['tenant_id', '', '', self::EXISTS_VALIDATE, 'integer'], // 租户id
        ['project_id', '', '', self::EXISTS_VALIDATE, 'integer'],
        ['entity_id', '', '', self::EXISTS_VALIDATE, 'integer'],
        ['project_id', '', '', self::EXISTS_VALIDATE, 'integer'],
        ['task_id', '', '', self::EXISTS_VALIDATE, 'integer'],
        ['step_category_id', '', '', self::EXISTS_VALIDATE, 'integer'],
        ['step_id', '', '', self::EXISTS_VALIDATE, 'integer'],
        ['repair_step_category_id', '', '', self::EXISTS_VALIDATE, 'integer'],
        ['repair_step_category_id', '', '', self::MUST_VALIDATE, 'require', self::MODEL_INSERT],//必须字段
        ['task_id', '', '', self::MUST_VALIDATE, 'require', self::MODEL_INSERT],//必须字段

    ];

    //自动完成
    protected $_auto = [
        ['tenant_id', 'auto_fill_tenant_id', self::MODEL_INSERT, 'function'],
        ['submitter_id', 'fill_created_by', self::MODEL_INSERT, 'function'],
        ['created_by', 'fill_created_by', self::MODEL_INSERT, 'function'],
        ['created', 'time', self::MODEL_INSERT, 'function'],
        ['updated', 'time', self::MODEL_BOTH, 'function'],
        ['json', 'json_encode', self::EXISTS_VALIDATE, 'function'],
    ];

    /**
     * 获取器：创建时间
     * @param $value
     * @param $data
     * @return array|mixed
     */
//    public function getCreatedAttr($value, $data)
//    {
//        if (!empty($value)) {
//            return get_format_date($value, 1);
//        }
//        return "";
//    }
    /**
     * 获取器：自定义字段
     * @param $value
     * @param $data
     * @return array|mixed
     */
    public function getJsonAttr($value, $data)
    {
        // 当前模块的自定义字段配置
        $currentModuleCode = \request()->getModuleCode();
        $fieldDict = Module::$moduleDictData['field_index_by_code']['task_repair_order']['custom'];

        // 判断是否有值
        if (!empty($value)) {
            $jsonDictData = json_decode($value, true);
        } else {
            $jsonDictData = [];
        }

        // 把自定义值写入追加字段
        foreach ($fieldDict as $filed => $config) {
            if (array_key_exists($filed, $jsonDictData)) {
                $this->appendCustomField[$filed] = $jsonDictData[$filed];
            } else {
                // 没有值赋空值
                $this->appendCustomField[$filed] = "";
            }
        }

        return $jsonDictData;
    }
}
